//
//  YSProductListCtrl.m
//  Yueshi
//
//  Created by Northwan on 15/7/21.
//  Copyright (c) 2015年 悦食中国. All rights reserved.
//

#import "YSProductListCtrl.h"
#import "YSCategoryDataTool.h"
#import "YSProductListGridItemCell.h"
#import "YSProductListItemCell.h"
#import "YSProductDetailCtrl.h"
#import "CustomShowView.h"
#import "YSSubProductCategoryView.h"
#import "YSProductCategory.h"
#import "CartView.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "YSBusinessHeaderView.h"
#import "YSProductPoolBigModeHeaderView.h"
#import "YSShareView.h"
#import "YSShareModel.h"

@interface YSProductListCtrl ()<UICollectionViewDataSource,UICollectionViewDelegate,UITableViewDataSource,UITableViewDelegate,YSSubProductCategoryViewDelegate,CustomShowViewDelegate>
@property(nonatomic,weak) UICollectionView *collectionView;
@property(nonatomic,strong) UITableView *tableView;
@property (strong, nonatomic) UIButton *backTopBtn;;

@property (weak, nonatomic) IBOutlet UIView *titleView;
@property (weak, nonatomic) IBOutlet UIButton *priceBtn;
@property (weak, nonatomic) IBOutlet UIButton *salesBtn;
@property (weak, nonatomic) IBOutlet UIButton *wholeBtn;
@property (weak, nonatomic) IBOutlet UIButton *viewModelBtn;

@property (copy, nonatomic) NSString *titleText;
@property (assign, nonatomic) NSInteger categoryId;
@property (assign, nonatomic) BrandWithCategoryPoolType type;
@property (copy, nonatomic) NSString *sortFile;
@property (copy, nonatomic) NSString *seque;
@property (assign, nonatomic) NSInteger pageIndex;

@property (strong, nonatomic) NSMutableArray *itemArray;
@property (strong, nonatomic) NSMutableArray *categoryArray;

@property (strong, nonatomic) CustomShowView *showView;
@property (strong, nonatomic) CartView *cartView;

@property (assign, nonatomic) NSInteger salesClickNum;
@property (assign, nonatomic) NSInteger priceClickNum;

@property (strong, nonatomic) YSProductListRes *result;
@property (assign, nonatomic) BOOL isAnimation;
@property (assign, nonatomic) CGFloat lastContentOffsetY;
@end

@implementation YSProductListCtrl

static NSString * const reuseIdentifier = @"YSProductListItemCell";
static NSString *const headerReuseIdentifier = @"YSBusinessHeaderView";

-(NSMutableArray *)itemArray{
    if(!_itemArray){
        _itemArray =  [NSMutableArray array];
    }
    return _itemArray;
}

-(NSMutableArray *)categoryArray{
    if(!_categoryArray){
        _categoryArray =  [NSMutableArray array];
    }
    return _categoryArray;
}

-(instancetype)initWithTitle:(NSString *)title categoryId:(NSInteger)categoryId type:(BrandWithCategoryPoolType)type{
    self = [super init];
    if(self){
        self.titleText = title;
        self.categoryId = categoryId;
        self.type = type;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:self.titleText];
    
    
    if(self.type == POOL_TYPE){
        NSMutableArray *leftItems =[NSMutableArray array];
        UIBarButtonItem *backItem =  [UIBarButtonItem itemWithImageName:@"nav_return_normal" highImageName:@"nav_return_normal" target:self action:@selector(tapBack:)];
        [leftItems addObject:backItem];
        
        UIImage *more = [UIImage imageNamed:@"icon_share_more"];
        UIButton *shareBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, more.size.width*2, more.size.height)];
        [shareBtn setImage:more forState:UIControlStateNormal];
//        [shareBtn sizeToFit];
        [shareBtn addTarget:self action:@selector(tapShare:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *shareItem =  [[UIBarButtonItem alloc]initWithCustomView:shareBtn];;
        [leftItems addObject:shareItem];
        self.navigationItem.leftBarButtonItems = leftItems;
    }
    
    CartView *cartView = [[CartView alloc]initWithImage:@"btn_cart"];
    [cartView addTarget:self action:@selector(tapTitleRightItem:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem =  [[UIBarButtonItem alloc]initWithCustomView:cartView];
    _cartView = cartView;
    
    _seque = @"";
    _sortFile = @"";
    [_wholeBtn setSelected:YES];
    [self updateWholeBtnImagePostion];
    [self initTableView];
    [self initCollectionView];
    [self.tableView.header beginRefreshing];
    
    _backTopBtn = [[UIButton alloc]init];
    _backTopBtn.frame = CGRectMake(SCREENW-50, SCREENH-150, 40, 40);
    [_backTopBtn setBackgroundImage:[UIImage imageNamed:@"icon_back_top"] forState:UIControlStateNormal];
    [_backTopBtn addTarget:self action:@selector(toTop:) forControlEvents:UIControlEventTouchUpInside];
    [self.view insertSubview:_backTopBtn aboveSubview:self.view];
}

-(void)tapShare:(UIButton *)sender{
    NSLog(@"%s",__FUNCTION__);
    YSShareModel *sm = [YSShareModel new];
    [sm setUrl:_result.shareLink];
    [sm setTitle:_result.title];
    [sm setSubTile:_result.topInfo];
    [sm setImageUrl:_result.topImage];
    YSShareView *sv = [[YSShareView alloc]init];
    [sv setWidth:SCREENW];
    [sv setShareModel:sm];
    CustomShowView *alertView =  [[CustomShowView alloc]initWithCustomView:sv location:CustomShowViewLocationTopType];
    [alertView showWithAnim:YES];
}

-(void)tapBack:(UIBarButtonItem *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)tapTitleRightItem:(UIBarButtonItem *)btnItem{
    [Utils showCartCtrl:self];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(_cartView){
        NSInteger num =  [DefaultsHelper integerForKey:kCartIndex];
        [_cartView setNum:num];
    }
}

-(void)updateWholeBtnImagePostion{
    //把这个小箭头放在销量的btn上是为了更好的适配，目前我只能想到这种解决方案
    [_salesBtn setImage:[UIImage imageNamed:@"icon_category_d"] forState:UIControlStateNormal];
    NSInteger wholeBtnTitleLength =  _wholeBtn.titleLabel.text.length;
    CGFloat imgEdgeInsetLeft = -_salesBtn.width;
    if(wholeBtnTitleLength == 2||wholeBtnTitleLength == 1){
        imgEdgeInsetLeft = -_salesBtn.width;
    }else if(wholeBtnTitleLength == 3){
        imgEdgeInsetLeft = -(_salesBtn.width-YSPublicXInset);
    }else if(wholeBtnTitleLength == 4){
        imgEdgeInsetLeft = -(_salesBtn.width-YSPublicXInset*2);
    }else{
        imgEdgeInsetLeft = -(_salesBtn.width-YSPublicXInset*3);
    }
    [_salesBtn setImageEdgeInsets:UIEdgeInsetsMake ( 0,
                                                    imgEdgeInsetLeft,
                                                    0,
                                                    0)];
}

-(void)hideWithCallBack {
    [self updateWholeBtnImagePostion];
}

-(void)toTop:(UIButton *)toTopBtn{
    if(self.collectionView.hidden){
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]
                              atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }else{
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:YES];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if(scrollView.contentOffset.y>scrollView.height){
        [_backTopBtn setHidden:NO];
    }else{
        [_backTopBtn setHidden:YES];
    }
    
//    if (scrollView.contentOffset.y <= scrollView.contentSize.height) {
//        _isAnimation = _lastContentOffsetY < scrollView.contentOffset.y;
//        _lastContentOffsetY = scrollView.contentOffset.y;
//    }
}

-(void)initTableView{
     self.tableView = [[UITableView alloc]init];
    if (_type == POOL_TYPE) {
        self.titleView.hidden = YES;
        [self.tableView setFrame:CGRectMake(0, 0, SCREENW, SCREENH-NavWithStatusBarH)];
    }else {
        [self.tableView setFrame:CGRectMake(0, CGRectGetMaxY(self.titleView.frame), SCREENW, SCREENH-NavWithStatusBarH-self.titleView.height)];
    }
    
    [self.tableView setBackgroundColor:PUBLIC_BG];
    [self.tableView setDelegate:self];
    [self.tableView setDataSource:self];
    [self.tableView registerNib:[UINib nibWithNibName:@"YSProductListItemCell" bundle:nil] forCellReuseIdentifier:@"YSProductListItemCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    header.lastUpdatedTimeLabel.hidden = YES;
    _tableView.header = header;
    self.tableView.footer  = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    [self.view addSubview:self.tableView];
}

-(void)initCollectionView{
    UICollectionViewFlowLayout *flowLayout =[[UICollectionViewFlowLayout alloc]init];
    [flowLayout setMinimumLineSpacing:5];
    [flowLayout setMinimumInteritemSpacing:5];
    UICollectionView *collectionView  =[[UICollectionView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.titleView.frame), SCREENW, SCREENH) collectionViewLayout:flowLayout];
    collectionView.height = collectionView.height-self.titleView.height-NavWithStatusBarH;
    [collectionView setBackgroundColor:PUBLIC_CARD_BG];
    [collectionView registerClass:[YSProductListGridItemCell class] forCellWithReuseIdentifier:reuseIdentifier];
    
    //注册头部View
    [collectionView  registerClass:[YSBusinessHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerReuseIdentifier];
    
    [collectionView setDelegate:self];
    [collectionView setDataSource:self];
    [collectionView setAlwaysBounceVertical:YES];
    [collectionView registerNib:[UINib nibWithNibName:reuseIdentifier bundle: [NSBundle mainBundle]] forCellWithReuseIdentifier:reuseIdentifier];
    [self.view addSubview:collectionView];
    [collectionView setHidden:YES];
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    header.lastUpdatedTimeLabel.hidden = YES;
    collectionView.header = header;
    collectionView.footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    self.collectionView = collectionView;
}

-(void)headerRefresh{
    self.pageIndex = 0;
    [self requestData];
}

-(void)footerRefresh{
    self.pageIndex ++;
    [self requestData];
}

-(void)switchProdList{
    BOOL hidden = _tableView.hidden;
    _tableView.hidden = !hidden;
    _collectionView.hidden =hidden;
    if(hidden)
      [self.viewModelBtn setImage:[UIImage imageNamed:@"icon_check_small"] forState:UIControlStateNormal];
    else
        [self.viewModelBtn setImage:[UIImage imageNamed:@"icon_check_big"] forState:UIControlStateNormal];
}

-(void)requestData{
    [YSCategoryDataTool getProductList:self.categoryId type:_type pageIndex:_pageIndex sortFile:_sortFile seque:_seque success:^(YSProductListRes *result) {
        [self recomleteRefresh];
        if(result.isSucc){
            _result = result;
            [self.navigationItem setTitle:result.title];
            if(self.pageIndex == 0){
                [self.itemArray removeAllObjects];
                [self.categoryArray removeAllObjects];
                [self.categoryArray addObjectsFromArray:result.productCategory];
                //如果分类只有一个全部就隐藏小箭头
                if(!self.categoryArray.count){
                    [self.salesBtn setImage:nil forState:UIControlStateNormal];
                }
                if(_type == POOL_TYPE){//如果是池子的列表，就判断是否要显示头图
                    //大图模式的header
                    YSProductPoolBigModeHeaderView *headerView = [[YSProductPoolBigModeHeaderView alloc]init];
                   if(!ISBLANK(result.topImage)&&!ISBLANK(result.topInfo)){
                        [headerView setInfoWithTopImage:_result.topImage topInfo:_result.topInfo];
                        [self.tableView setTableHeaderView:headerView];
                   }else if(!ISBLANK(result.topInfo)){
                        [headerView setTopInfo:_result.topInfo];
                        [self.tableView setTableHeaderView:headerView];
                   }
                }
            }
            
            [self.itemArray addObjectsFromArray:result.productList];
            [self.collectionView reloadData];
            [self.tableView reloadData];
        }else{
            ShowEnterTips(result.data);
        }
    } failure:^(NSError *error) {
        [self recomleteRefresh];
        ShowTips(kRequestFailure);
    }];
}

-(void)recomleteRefresh{
    if(self.collectionView.hidden){
        [UIUtil refreshComplete:self.tableView];
    }else{
        [self.collectionView.header endRefreshing];
        [self.collectionView.footer endRefreshing];
    }
}

#pragma mark <UICollectionViewDataSource>
//返回header
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"indexPath = %@",indexPath);
    if(_type == POOL_TYPE){
         YSBusinessHeaderView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerReuseIdentifier forIndexPath:indexPath];
        if(!ISBLANK(_result.topImage)&&!ISBLANK(_result.topInfo)){
            [headView setInfoWithTopImage:_result.topImage topInfo:_result.topInfo];
            return headView;
        }else if (!ISBLANK(_result.topInfo)){
            [headView setTopInfo:_result.topInfo];
            return headView;
        }
    }
    return nil;
}
//返回header的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
      if(_type == POOL_TYPE){
          if(!ISBLANK(_result.topImage)&&!ISBLANK(_result.topInfo)){
             CGSize size = [_result.topInfo sizeWithFont:SYS_FONT(15) constrainedToSize:CGSizeMake(SCREENW, MAXFLOAT)];
             return CGSizeMake(SCREENW, HeaderImgHeight+size.height+YSPublicXInset*3);
          }else if (!ISBLANK(_result.topInfo)){
              CGSize size = [_result.topInfo sizeWithFont:SYS_FONT(15) constrainedToSize:CGSizeMake(SCREENW, MAXFLOAT)];
              return CGSizeMake(SCREENW, size.height+YSPublicXInset*5);
          }
     }
    return CGSizeZero;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.itemArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    YSProductListGridItemCell *cell = [YSProductListGridItemCell cellWithCollectionView:collectionView indexPath:indexPath];
    [cell setProd:self.itemArray[indexPath.row]];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((SCREENW-25)/2, 250);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger prodId = [self.itemArray[indexPath.row] prodId];
    YSProductDetailCtrl *ctrl =  [[YSProductDetailCtrl alloc]initWithProdId:prodId];
    [self.navigationController pushViewController:ctrl animated:YES];
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10,10,10,10);
}

-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
//    if (_isAnimation){
//        [self cellDisplayWithAnimation:cell offsetY:80 duration:0.5];
//    }
}

#pragma - mark UITableViewDataSource,UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.itemArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YSProductListItemCell *cell =  [YSProductListItemCell cellWithTableView:tableView];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setProd:self.itemArray[indexPath.row]];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [tableView fd_heightForCellWithIdentifier:@"YSProductListItemCell" cacheByIndexPath:indexPath configuration:^(YSProductListItemCell *cell) {
        [cell setProd:self.itemArray[indexPath.row]];
    }];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSInteger prodId = [self.itemArray[indexPath.row] prodId];
    YSProductDetailCtrl *ctrl =  [[YSProductDetailCtrl alloc]initWithProdId:prodId];
    [self.navigationController pushViewController:ctrl animated:YES];
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
//    if (_isAnimation){
//       [self cellDisplayWithAnimation:cell offsetY:80 duration:0.5];
//    }
}

-(void)initPriceSort{
    _sortFile = @"";
    _seque = @"";
    _priceClickNum = 0;
    [_priceBtn setSelected:NO];
    [_priceBtn setImage:nil forState:UIControlStateNormal];
}

-(void)initSalesSort{
    _sortFile = @"";
    _seque = @"";
    _salesClickNum = 0;
    [_salesBtn setSelected:NO];
}

-(void)cellDisplayWithAnimation:(UIView *)view offsetY:(CGFloat)offsetY duration:(NSTimeInterval)duration{
    view.transform = CGAffineTransformMakeTranslation(0, offsetY);
    view.alpha = 0.0;
    [UIView animateWithDuration:duration animations:^{
        view.transform = CGAffineTransformIdentity;
        view.alpha = 1;
    }];
}

- (IBAction)tapTitleItem:(UIButton *)sender {
    
    switch (sender.tag) {
        case 0:{//价格：price
            [self initSalesSort];
            if(_priceClickNum == 0){
                _sortFile = @"price";
                _seque = @"asc";
                _priceClickNum++;
                [_priceBtn setSelected:YES];
                 self.priceBtn.imageView.transform = CGAffineTransformIdentity;
                [_priceBtn setImage:[UIImage imageNamed:@"icon_prodlist_down"] forState:UIControlStateNormal];
                 _priceBtn.imageEdgeInsets = UIEdgeInsetsMake(0, _priceBtn.width-YSPublicXInset*2, 0, 0);
                self.priceBtn.imageView.transform = CGAffineTransformMakeRotation(0.000001 - M_PI);
            }else if (_priceClickNum == 1){
                _sortFile = @"price";
                _seque = @"desc";
                _priceClickNum++;
                [_priceBtn setSelected:YES];
                
                [UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^{
                    self.priceBtn.imageView.transform = CGAffineTransformMakeRotation(0.000001 - M_PI);
                    self.priceBtn.imageView.transform = CGAffineTransformIdentity;
                }];
                
            }else{
                _sortFile = @"";
                _seque = @"";
                _priceClickNum = 0;
                [_priceBtn setSelected:NO];
                [_priceBtn setImage:nil forState:UIControlStateNormal];
            }
             [self.salesBtn setSelected:NO];
            [self useViewHeaderBeginRefresh];
            break;
        }
        case 1:{//销量：sales
            [self initPriceSort];
            if (_salesClickNum == 0){
                 _sortFile = @"sales";
                _seque = @"desc";
                _salesClickNum++;
                 [_salesBtn setSelected:YES];
            }else{
                _sortFile = @"";
                _seque = @"";
                _salesClickNum = 0;
                [_salesBtn setSelected:NO];
            }
            [self.priceBtn setSelected:NO];
            [self useViewHeaderBeginRefresh];
            break;
        }
        case 2:{//全部
            _sortFile = @"";
            if(self.categoryArray.count){
                UIImage *upimage = [UIImage imageNamed:@"icon_category_u"];
                [_salesBtn setImage:upimage forState:UIControlStateNormal];
                if(_showView){
                    if([_showView isShowing]){
                        [_showView hideWithAnim:YES];
                    }else{
                        [_showView showWithAnim:YES isTransparent:YES];
                    }
                }else{
                    [_priceBtn setSelected:NO];
                    [_salesBtn setSelected:NO];
                    if(self.categoryArray.count){
                        //二级分类View
                        YSSubProductCategoryView *subCategoryView =  [[YSSubProductCategoryView alloc]initWithCategoryArray:self.categoryArray];
                        [subCategoryView setDelegate:self];
                        [subCategoryView setFrame:CGRectMake(0, 0, SCREENW, subCategoryView.height)];
                        [subCategoryView setBackgroundColor:PUBLIC_BG];
                        CGPoint point = CGPointMake(0,NavWithStatusBarH+40);
                        CustomShowView *showView = [[CustomShowView alloc]initWithCustomView:subCategoryView point:point];
                        [showView setDelegate:self];
                        [showView showWithAnim:YES isTransparent:YES];
                        _showView = showView;
                    }
                }
            }else{
                [self useViewHeaderBeginRefresh];
            }
            break;
        }
        case 3:{//切换显示模式
            [self switchProdList];
            break;
        }
        default:
            break;
    }
}

-(void)categoryItemClick:(NSInteger)categoryId{
    [self updateWholeBtnImagePostion];
    for (YSProductCategory *category in _categoryArray) {
        if(categoryId == category.categoryId){
            [self.wholeBtn setTitle:category.categoryName forState:UIControlStateNormal];
            break;
        }
    }
    self.categoryId = categoryId;
    [self useViewHeaderBeginRefresh];
}

-(void)useViewHeaderBeginRefresh{
    if(self.collectionView.hidden){
        [self.tableView.header beginRefreshing];
    }else{
        [self.collectionView.header beginRefreshing];
    }
}

@end
